package com.alliky.core.net;

import android.os.Build;

import androidx.annotation.RequiresApi;

import com.alliky.core.BuildConfig;
import com.alliky.core.config.Config;
import com.alliky.core.global.Global;
import com.alliky.core.net.converter.BaseConverterFactory;
import com.alliky.core.net.interceptor.BodyInterceptor;
import com.alliky.core.net.interceptor.CacheInterceptor;
import com.alliky.core.net.interceptor.HttpLogInterceptor;
import com.alliky.core.net.interceptor.RequestParameterInterceptor;
import com.alliky.core.net.interceptor.logger.Level;
import com.alliky.core.net.interceptor.logger.LoggingInterceptor;
import com.alliky.core.util.AesUtil;
import com.alliky.core.util.KLog;
import com.alliky.core.util.StringUtils;
import com.tamsiree.rxkit.RxDeviceTool;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

@RequiresApi(api = Build.VERSION_CODES.N)
public class RxRetrofit {

    private static Retrofit mInstance = null;

    public static Retrofit getInstance() {
        if (mInstance == null) {
            synchronized (RxRetrofit.class) {
                if (mInstance == null) {
                    mInstance = new Retrofit.Builder()
                            .baseUrl(Config.getBaseUrl())
                            .client(getOkHttpClient())
//                            .addConverterFactory(GsonConverterFactory.create())
                            .addConverterFactory(BaseConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build();
                }
            }
        }
        return mInstance;
    }


    private static OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        Level level = Level.NONE;
        if (BuildConfig.DEBUG) {
            level = Level.HEADERS;
        }
//        LoggingInterceptor mLoggingInterceptor = new LoggingInterceptor
//                .Builder()//构建者模式
//                .loggable(true) //是否开启日志打印
//                .setLevel(level) //打印的等级
//                .log(Platform.INFO) // 打印类型
//                .request("Request") // request的Tag
//                .response("Response")// Response的Tag
//                .addHeader("timestamp", BuildConfig.VERSION_NAME)//打印版本
//                .addHeader("client_device", BuildConfig.VERSION_NAME)//打印版本
//                .addHeader("version_name", BuildConfig.VERSION_NAME)//打印版本
//                .addHeader("device_number", BuildConfig.VERSION_NAME)//打印版本
//                .addHeader("token", BuildConfig.VERSION_NAME)//打印版本
//                .addHeader("sign", AesUtil.setSign2())//打印版本
//                .build();


        LoggingInterceptor.Builder logBuilder = new LoggingInterceptor.Builder();

        logBuilder.loggable(true);
        logBuilder.setLevel(level);
        logBuilder.log(Platform.INFO);
        logBuilder.request("Request");
        logBuilder.response("Response");

        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        HashMap<String, String> hashMap = new HashMap();

        hashMap.put("timestamp", timestamp);
        hashMap.put("device", "android");
        hashMap.put("version", RxDeviceTool.getAppVersionName(Config.getApplicationContext()));
        if (StringUtils.isBlank(Global.UserManage.getToken())) {
            hashMap.put("token", Global.UserManage.getToken());
        }
        hashMap.put("sign", AesUtil.setSign2(hashMap));
        hashMap.forEach((k, v) -> {
            logBuilder.addHeader(k, v);
        });
        //添加头部
        builder.addInterceptor(logBuilder.build());
        HttpLogInterceptor interceptor = new HttpLogInterceptor(message -> KLog.d("X_HTTP", message));
        interceptor.setLevel(HttpLogInterceptor.Level.BODY);
        interceptor.setLevel(HttpLogInterceptor.Level.BODY);
//        builder.addInterceptor(new BodyInterceptor());

        builder.addInterceptor(interceptor);
        builder.addInterceptor(new CacheInterceptor(Config.getApplicationContext()));

        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(15, TimeUnit.SECONDS);
        builder.writeTimeout(15, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);

        // 构建 OkHttpClient 时,将 OkHttpClient.Builder() 传入 with() 方法,进行初始化配置
        return RetrofitUrlManager.getInstance().with(builder).build();
    }
}
